rm(list = ls())
library(countrycode)
library(pscl)
library(foreign)
setwd("~/Desktop/QJPS Replication")

data <- read.csv("data/roll_call_matrix.csv")
data <- data[order(data$cowcode),]

##Miller et all democracy data
dem <- read.dta13("data/ccpcnc_v2_small.dta")

#combine democracy data with roll call matrix
data$match <- paste(data$cowcode, data$year)
dem$match <- paste(dem$cowcode, dem$year)
m <- match(data$match, dem$match)
table(is.na(m))

dem$country <- as.character(dem$country)
data$country_name <- dem$country[m]
data$country_name <- as.character(data$country_name)

#get rid of Mexico
data <- data[data$country_name != "Mexico",]

#subset data to only those that had a change occur
#some of the original data are missing because the CCP 
#authors haven't coded it yet. For example, the Bahamas only enter the datset in 2002, 
#but became a country in 1973.
data2 <- data[data$evnt == 1,]
data2 <- data2[,11:(ncol(data2)-3)]

#How many missing values are there for each entry
num.missing <- apply(data2, 1, function(x)sum(ifelse(is.na(x), 1, 0)))
prop.missing <- num.missing / ncol(data2)

#Get rid of those entries with more than 90 percent missing values
data3 <- data2[prop.missing < .9,]

#make the matrix a roll call object
mat <- rollcall(data3, yea = 1, nay = 0, legis.names = rownames(data3), vote.names = colnames(data3))

#scale the country-feature matrix using 2-dimensional WNOMINATE method
set.seed(4227492)
idealpoints2 <- wnominate(mat, dims = 2, polarity = c(1,1))

#Use the 112th House for a comparison of a 1 dimensional body.
house <- read.dta("data/hou112kh.dta")

#make the matrix a roll call object
house2 <- rollcall(house[,10:ncol(house)], yea = c(1,2,3), nay = c(4,5,6), notInLegis = c(0,7,8,9))

#scale the legisaltor-vote matrix using 2-dimensional WNOMINATE method
set.seed(4227492)
house.idealpoints <- wnominate(house2, dims = 2, polarity = c(1,1))



######################
#Figure A7 - top panel
######################
plot.angles(idealpoints2, axes = F, dims = c(1,2))
axis(1, seq(10, 180, 20))
axis(2, seq(0, 500, 10), las = 2)
box()
dev.off()



#########################
#Figure A7 - bottom panel
#########################
plot.angles(house.idealpoints, axes = F, dims = c(1,2), main = "112th U.S. House: Cutting Line Angles")
axis(1, seq(10, 180, 20))
axis(2, seq(0, 500, 40), las = 2)
box()
